var bg = chrome.extension.getBackgroundPage();
var G = bg.SINA;

var Setting = JSON.parse(G.get("longSetting"));

var comment_api_url = bg.APIV.comments.to_me;
var mention_api_url = bg.APIV.comments.mentions; //获取@到我的评论
var at_mention_api_url = bg.APIV.statuses.mentions;
var follower_api_url = bg.APIV.friendships.followers;
var short_url_info = bg.APIV.short_url.info;
var topics_api_url = bg.APIV.search.topics;
var statuses_api_url = bg.APIV.statuses.friends_timeline; //获取最新微博
var user_timeline = bg.APIV.statuses.user_timeline;
var emotions = JSON.parse(G.get('emotions_tpl'));
var SENDING = false;

function generateFollowerDiv(follower) {
	var data = {
		id : follower.id,
		screen_name : follower.screen_name,
		profile_image_url : follower.profile_image_url,
		followers_count : follower.followers_count,
		friends_count : follower.friends_count,
		statuses_count : follower.statuses_count,
		following : eval(follower.following) ? "取消" : "",
		verified : (follower.verified ? '<img src="/maincss/v.gif" alt="V">' : ''),
		description : follower.description,
		gender : follower.gender,
		location : follower.location
	};
	var html = G.replaceAll(followTpl, data);
	return html;
}

function generateStatusDiv(statuses, zf) {
	if (statuses.deleted && statuses.deleted === "1")
		return "";
	var data = {
		id : statuses.id,
		text : replace_face(statuses.text),
		source : statuses.source,
		favorited : statuses.favorited ? '已' : '',
		reposts_count : statuses.reposts_count,
		comments_count : statuses.comments_count,
		screen_name : statuses.user.screen_name,
		uid : statuses.user.id,
		followers_count : statuses.user.followers_count,
		friends_count : statuses.user.friends_count,
		statuses_count : statuses.user.statuses_count,
		following : statuses.user.following ? "取消关注" : "关注",
		verified_reason : statuses.user.verified_reason || statuses.user.description,
		profile_image_url : statuses.user.profile_image_url,
		created_at : G.dateDiff(new Date(statuses.created_at).getTime()),
		verified : statuses.user.verified ? '<img src="/maincss/v.gif" alt="V">' : '',
		retweeted : (statuses['retweeted_status'] ? generateStatusDiv(statuses.retweeted_status, true) : ''),
		media : (statuses['original_pic'] ? generatestatusMedia(statuses) : '')
	};

	var html = G.replaceAll(zf ? statusDivZfTpl : statusDivTpl, data);
	return html;
}

var reg = /\[.+?\]/ig;
var regat = /@[\u4e00-\u9fa5\w\-]+/ig;
var regtopic = /#([^\#|.]+)#/ig;
var regurl = /[a-zA-z]+:\/\/[^\s^\u4e00-\u9fa5]*/ig

function replace_face(text) {
	var face = text.match(reg);
	var at = text.match(regat);
	var topic = text.match(regtopic);
	var url = text.match(regurl);
	if (face && face.length) {
		for (var i = 0; i < face.length; i++) {
			text = text.replace(face[i], emotions[face[i]]);
		}
	}
	if (at && at.length) {
		at = $.unique(at);
		for (var i = 0; i < at.length; i++) {
			text = text.replace(new RegExp(at[i], "gm"), "<a  onMouseover='get_user_info(this," + at[i].replace("@", "") + ")' onclick='showStatus(this," + at[i].replace("@", "") + ")'>" + at[i] + "</a>");
		}
	}
	if (topic && topic.length) {
		topic = $.unique(topic);
		for (var i = 0; i < topic.length; i++) {
			text = text.replace(new RegExp(topic[i], "gm"), "<a onclick='showTopic(this)'>" + topic[i] + "</a>");
		}
	}
	if (url && url.length) {
		url = $.unique(url);
		for (var i = 0; i < url.length; i++) {
			text = text.replace(url[i], "<a onclick='jumpUrl(this)'>" + url[i] + "</a>");
		}
	}
	return text;
}

function get_user_info(target, name) {
	if (!$(target).attr("title") && $(target).attr("title") != "加载ing") {
		$(target).attr("title", "加载ing");
		G.gets(bg.APIV.users.show, {
			screen_name : name
		}, function (rsp) {
			if (!rsp.error) {
				var title = "关注：{{friends_count}}\r\n粉丝：{{followers_count}}\r\n微博：{{statuses_count}}\r\n简介：{{description}}";
				title = G.replaceAll(title, rsp);
				$(target).attr("title", title);
			}
		});
	}
}

function generateCommentsDiv(statuses, zf) {
	if (statuses.deleted && statuses.deleted === "1")
		return "";
	var data = {
		id : statuses.id,
		text : replace_face(statuses.text),
		source : statuses.source,
		favorited : statuses.favorited ? '已' : '',
		reposts_count : statuses.reposts_count || 0,
		comments_count : statuses.comments_count || 0,
		screen_name : statuses.user.screen_name,
		uid : statuses.user.id,
		followers_count : statuses.user.followers_count,
		friends_count : statuses.user.friends_count,
		statuses_count : statuses.user.statuses_count,
		following : statuses.user.following ? "取消关注" : "关注",
		verified_reason : statuses.user.verified_reason || statuses.user.description,
		mid : (statuses['status'] ? statuses.status.id : ''),
		profile_image_url : statuses.user.profile_image_url,
		created_at : G.dateDiff(new Date(statuses.created_at).getTime()),
		verified : statuses.user.verified ? '<img src="/maincss/v.gif" alt="V">' : '',
		retweeted : (statuses['status'] ? generateCommentsDiv(statuses.status, true) : ''),
		media : (statuses['original_pic'] ? generatestatusMedia(statuses) : '')
	};

	var html = G.replaceAll(zf ? statusNoCtrDivTpl : statusCmtDivTpl, data);
	return html;
}

/**
 *@我的评论
 */
function generateArmeCommentsDiv(statuses, zf) {
	if (statuses.deleted && statuses.deleted === "1")
		return "";
	var data = {
		id : statuses.id,
		text : replace_face(statuses.text),
		source : statuses.source,
		favorited : statuses.favorited ? '已' : '',
		reposts_count : statuses.reposts_count || 0,
		comments_count : statuses.comments_count || 0,
		screen_name : statuses.user.screen_name,
		uid : statuses.user.id,
		followers_count : statuses.user.followers_count,
		friends_count : statuses.user.friends_count,
		statuses_count : statuses.user.statuses_count,
		following : statuses.user.following ? "取消关注" : "关注",
		verified_reason : statuses.user.verified_reason || statuses.user.description,
		mid : (statuses['status'] ? statuses.status.id : ''),
		profile_image_url : statuses.user.profile_image_url,
		created_at : G.dateDiff(new Date(statuses.created_at).getTime()),
		verified : statuses.user.verified ? '<img src="/maincss/v.gif" alt="V">' : '',
		retweeted : (statuses['status'] ? generateArmeCommentsDiv(statuses.status, true) : ''),
		media : (statuses['original_pic'] ? generatestatusMedia(statuses) : '')
	};

	var html = G.replaceAll(zf ? statusNoCtrDivTpl : statusAtMeCmtDivTpl, data);
	return html;
}

function generatestatusMedia(statuses) {
	var html = G.replaceAll(statusImgTpl, statuses);
	return html;
}

function showLarge(target) {
	$(target).hide().next().show();
}
function hideLarge(target) {
	$(target).hide().prev().show();
}

function doReposts(id, num) {
	num = parseInt(num);
	var _wbr = $("#wb_" + id, $('div.tabpage:visible')).children('div.wb_r');
	var plwrap = $(">div.plWrap", _wbr);
	var zfwrap = $(">div.zfWrap", _wbr);
	if (plwrap.length) {
		plwrap.remove();
	}
	if (zfwrap.length) {
		zfwrap.remove();
	} else {
		zfwrap = G.replaceAll(zfwrapTpl, {
				id : id
			});
		_wbr.append(ReplaceMethos(zfwrap));
		var _relist = $("#re_list_" + id, $('div.tabpage:visible'));
		if (num === 0) {
			return;
		}
		_relist.append('<div style="text-align:center;"><img src="/waiting.gif"/></div>');
		G.gets(bg.APIV.statuses.repost_timeline, {
			id : id
		}, function (rsp) {
			var _reposts = rsp.reposts;
			if (_reposts.length > 0) {
				var _list = [];
				for (var idx in _reposts) {
					var data = {
						page : 1,
						id : _reposts[idx].id,
						screen_name : _reposts[idx].user.screen_name,
						uid : _reposts[idx].user.id,
						followers_count : _reposts[idx].user.followers_count,
						friends_count : _reposts[idx].user.friends_count,
						statuses_count : _reposts[idx].user.statuses_count,
						following : _reposts[idx].user.following ? "取消关注" : "关注",
						verified_reason : _reposts[idx].user.verified_reason || _reposts[idx].user.description,
						text : replace_face(_reposts[idx].text),
						created_at : G.dateDiff(new Date(_reposts[idx].created_at).getTime()),
						profile_image_url : _reposts[idx].user.profile_image_url
					};
					_list.push(G.replaceAll(relistTpl, data));
				}
				_relist.html(ReplaceMethos(_list.join('')));
				if (rsp.total_number > 20) {
					_relist.after(ReplaceMethos(G.replaceAll(zfpageTpl, {
								id : id,
								prev : 0,
								next : 2,
								clazz : "hide",
								fclazz : "hide"
							})));
				}
			} else {
				_relist.remove();
			}
		});
	}
}

function doRepostsZf(id, num) {
	num = parseInt(num);
	var _wbr = $("#zf_" + id, $('div.tabpage:visible'));
	var plwrap = $(".plWrap", _wbr);
	var zfwrap = $(".zfWrap", _wbr);
	if (plwrap.length) {
		plwrap.remove();
	}
	if (zfwrap.length) {
		zfwrap.remove();
	} else {
		zfwrap = G.replaceAll(zfwrapTpl, {
				id : id
			});
		_wbr.append(ReplaceMethos(zfwrap));
		var _relist = $("#re_list_" + id, $('div.tabpage:visible'));
		if (num === 0) {
			return;
		}
		_relist.append('<div style="text-align:center;"><img src="/waiting.gif"/></div>');
		G.gets(bg.APIV.statuses.repost_timeline, {
			id : id
		}, function (rsp) {
			var _reposts = rsp.reposts;
			if (_reposts.length > 0) {
				var _list = [];
				for (var idx in _reposts) {
					var data = {
						page : 1,
						id : _reposts[idx].id,
						screen_name : _reposts[idx].user.screen_name,
						uid : _reposts[idx].user.id,
						followers_count : _reposts[idx].user.followers_count,
						friends_count : _reposts[idx].user.friends_count,
						statuses_count : _reposts[idx].user.statuses_count,
						following : _reposts[idx].user.following ? "取消关注" : "关注",
						verified_reason : _reposts[idx].user.verified_reason || _reposts[idx].user.description,
						text : replace_face(_reposts[idx].text),
						created_at : G.dateDiff(new Date(_reposts[idx].created_at).getTime()),
						profile_image_url : _reposts[idx].user.profile_image_url
					};
					_list.push(G.replaceAll(relistTpl, data));
				}
				_relist.html(ReplaceMethos(_list.join('')));
				if (rsp.total_number > 20) {
					_relist.after(ReplaceMethos(G.replaceAll(zfpageTpl, {
								id : id,
								prev : 0,
								next : 2,
								clazz : "hide",
								fclazz : "hide"
							})));
				}
			} else {
				_relist.remove();
			}
		});
	}
}

function doFavorited(target, id) {
	var text = $(target).text();
	var api_url = bg.APIV.favorites.create
		if (text !== '收藏') {
			api_url = bg.APIV.favorites.destroy;
		}

		G.post(api_url, {
			id : id
		}, function (rsp) {
			if (rsp.status && rsp.status.favorited) {
				$(target).text('已收藏');
			} else {
				$(target).text('收藏');
			}
		});
}

function doComment(id, num) {
	num = parseInt(num);
	var _wbr = $("#wb_" + id, $('div.tabpage:visible')).children('div.wb_r');
	var plwrap = $(">div.plWrap", _wbr);
	var zfwrap = $(">div.zfWrap", _wbr);
	if (zfwrap.length) {
		zfwrap.remove();
	}
	if (plwrap.length) {
		plwrap.remove();
	} else {
		plwrap = G.replaceAll(plwrapTpl, {
				id : id
			});
		_wbr.append(ReplaceMethos(plwrap));
		var _pllist = $("#comments_list_" + id, $('div.tabpage:visible'));
		if (num === 0) {
			return;
		}
		_pllist.append('<div style="text-align:center;"><img src="/waiting.gif"/></div>');
		G.gets(bg.APIV.comments.show, {
			id : id
		}, function (rsp) {
			var _comments = rsp.comments;
			if (_comments.length > 0) {

				var _list = [];
				for (var idx in _comments) {
					var data = {
						page : 1,
						id : _comments[idx].id,
						sid : _comments[idx].status.id,
						screen_name : _comments[idx].user.screen_name,
						uid : _comments[idx].user.id,
						followers_count : _comments[idx].user.followers_count,
						friends_count : _comments[idx].user.friends_count,
						statuses_count : _comments[idx].user.statuses_count,
						following : _comments[idx].user.following ? "取消关注" : "关注",
						verified_reason : _comments[idx].user.verified_reason || _comments[idx].user.description,
						text : replace_face(_comments[idx].text),
						created_at : G.dateDiff(new Date(_comments[idx].created_at).getTime()),
						profile_image_url : _comments[idx].user.profile_image_url
					};
					_list.push(G.replaceAll(pllistTpl, data));
				}
				_pllist.html(ReplaceMethos(_list.join('')));
				if (rsp.total_number > 50) {
					_pllist.after(ReplaceMethos(G.replaceAll(plpageTpl, {
								id : id,
								prev : 0,
								next : 2,
								clazz : "hide",
								fclazz : "hide"
							})));
				}
			} else {
				_pllist.remove();
			}
		});
	}
}

function doCommentCm(id, mid, screen_name) {
	var _wbr = $("#wb_" + id, $('div.tabpage:visible')).children('div.wb_r');
	var plwrap = $(">div.plWrap", _wbr);
	var zfwrap = $(">div.zfWrap", _wbr);
	if (zfwrap.length) {
		zfwrap.remove();
	}
	if (plwrap.length) {
		plwrap.remove();
	} else {
		plwrap = G.replaceAll(plrplwrapTpl, {
				id : id,
				mid : mid,
				screen_name : screen_name
			});
		_wbr.append(ReplaceMethos(plwrap));
	}
}

function doRePl(cid, wid, sname) {
	var rp = "回复@" + sname + ":";
	$("#plTxt_" + wid, $('div.tabpage:visible')).val(rp).focus();
	setCaretPosition($("#plTxt_" + wid, $('div.tabpage:visible'))[0], rp.length);
	$("#plTxt_warn_" + wid, $('div.tabpage:visible')).next("input").attr("onclick", "send_pl_rp(" + cid + "," + wid + ",true)");
	checkText('plTxt', wid, 140);
}

function setCaretPosition(ctrl, pos) {
	if (ctrl.setSelectionRange) {
		ctrl.focus();
		ctrl.setSelectionRange(pos, pos);
	} else if (ctrl.createTextRange) {
		var range = ctrl.createTextRange();
		range.collapse(true);
		range.moveEnd('character', pos);
		range.moveStart('character', pos);
		range.select();
	}
}

function doCommentZf(id, num) {
	num = parseInt(num);
	var _wbr = $("#zf_" + id, $('div.tabpage:visible'));
	var plwrap = $(".plWrap", _wbr);
	var zfwrap = $(".zfWrap", _wbr);
	if (zfwrap.length) {
		zfwrap.remove();
	}

	if (plwrap.length) {
		plwrap.remove();
	} else {
		plwrap = G.replaceAll(plwrapTpl, {
				id : id
			});
		_wbr.append(ReplaceMethos(plwrap));
		var _pllist = $("#comments_list_" + id, $('div.tabpage:visible'));
		if (num === 0) {
			return;
		}
		_pllist.append('<div style="text-align:center;"><img src="/waiting.gif"/></div>');
		G.gets(bg.APIV.comments.show, {
			id : id
		}, function (rsp) {
			var _comments = rsp.comments;
			if (_comments.length > 0) {
				var _list = [];
				for (var idx in _comments) {
					var data = {
						page : 1,
						id : _comments[idx].id,
						sid : _comments[idx].status.id,
						screen_name : _comments[idx].user.screen_name,
						uid : _comments[idx].user.id,
						followers_count : _comments[idx].user.followers_count,
						friends_count : _comments[idx].user.friends_count,
						statuses_count : _comments[idx].user.statuses_count,
						following : _comments[idx].user.following ? "取消关注" : "关注",
						verified_reason : _comments[idx].user.verified_reason || _comments[idx].user.description,
						text : replace_face(_comments[idx].text),
						created_at : G.dateDiff(new Date(_comments[idx].created_at).getTime()),
						profile_image_url : _comments[idx].user.profile_image_url
					};
					_list.push(G.replaceAll(pllistTpl, data));
				}
				_pllist.html(ReplaceMethos(_list.join('')));
				if (rsp.total_number > 50) {
					_pllist.after(ReplaceMethos(G.replaceAll(plpageTpl, {
								id : id,
								prev : 0,
								next : 2,
								clazz : "hide",
								fclazz : "hide"
							})));
				}
			} else {
				_pllist.remove();
			}
		});
	}
}

/**
 *关注某人
 */
function follow_one(target, id) {
	var type = $(target).text();
	var url = bg.APIV.friendships.create;
	if (type !== "关注") {
		url = bg.APIV.friendships.destroy;
	}

	G.post(url, {
		uid : id
	}, function (resp) {
		if (resp) {
			if (type === "关注") {
				$(target).text("取消关注");
			} else {
				$(target).text("关注");
			}
		}
	});
}

function get_comments(p, id) {
	p = parseInt(p);
	if (p == 0)
		return;
	var _pageWrap = $("#pl_list_page_" + id, $('div.tabpage:visible'));
	var _pllist = $("#comments_list_" + id, $('div.tabpage:visible'));
	_pllist.html('<div style="text-align:center;"><img src="/waiting.gif"/></div>');
	G.gets(bg.APIV.comments.show, {
		id : id,
		page : p
	}, function (rsp) {
		var _comments = rsp.comments;
		if (_comments.length > 0) {
			var _list = [];
			for (var idx in _comments) {
				var data = {
					page : p,
					id : _comments[idx].id,
					sid : _comments[idx].status.id,
					screen_name : _comments[idx].user.screen_name,
					uid : _comments[idx].user.id,
					followers_count : _comments[idx].user.followers_count,
					friends_count : _comments[idx].user.friends_count,
					statuses_count : _comments[idx].user.statuses_count,
					following : _comments[idx].user.following ? "取消关注" : "关注",
					verified_reason : _comments[idx].user.verified_reason || _comments[idx].user.description,
					text : replace_face(_comments[idx].text),
					created_at : G.dateDiff(new Date(_comments[idx].created_at).getTime()),
					profile_image_url : _comments[idx].user.profile_image_url
				};
				_list.push(G.replaceAll(pllistTpl, data));
			}
			_pllist.html(ReplaceMethos(_list.join('')));
		}
		var next = p;
		var totalPage = Math.ceil(rsp.total_number / 50);
		if (p != totalPage) {
			next = p + 1;
		}
		_pageWrap.replaceWith(ReplaceMethos(G.replaceAll(plpageTpl, {
					id : id,
					prev : p - 1,
					next : next,
					clasz : ((p == totalPage) ? "hide" : ""),
					clazz : ((p == 1) ? "hide" : ""),
					fclazz : ((p == 1) ? "hide" : ""),
					first : 1
				})));
	});
}

function get_reposts(p, id) {
	p = parseInt(p);
	if (p == 0)
		return;
	var _pageWrap = $("#re_list_page_" + id, $('div.tabpage:visible'));
	var _relist = $("#re_list_" + id, $('div.tabpage:visible'));
	_relist.html('<div style="text-align:center;"><img src="/waiting.gif"/></div>');
	G.gets(bg.APIV.statuses.repost_timeline, {
		id : id,
		page : p
	}, function (rsp) {
		var _reposts = rsp.reposts;
		if (_reposts.length > 0) {

			var _list = [];
			for (var idx in _reposts) {
				var data = {
					page : p,
					id : _reposts[idx].id,
					screen_name : _reposts[idx].user.screen_name,
					uid : _reposts[idx].user.id,
					followers_count : _reposts[idx].user.followers_count,
					friends_count : _reposts[idx].user.friends_count,
					statuses_count : _reposts[idx].user.statuses_count,
					following : _reposts[idx].user.following ? "取消关注" : "关注",
					verified_reason : _reposts[idx].user.verified_reason || _reposts[idx].user.description,
					text : replace_face(_reposts[idx].text),
					created_at : G.dateDiff(new Date(_reposts[idx].created_at).getTime()),
					profile_image_url : _reposts[idx].user.profile_image_url
				};
				_list.push(G.replaceAll(relistTpl, data));
			}
			_relist.html(ReplaceMethos(_list.join('')));
		}
		var next = p;
		var totalPage = Math.ceil(rsp.total_number / 20);
		if (p != totalPage) {
			next = p + 1;
		}
		_pageWrap.replaceWith(ReplaceMethos(G.replaceAll(zfpageTpl, {
					id : id,
					prev : p - 1,
					next : next,
					clasz : ((p == totalPage) ? "hide" : ""),
					clazz : ((p == 1) ? "hide" : ""),
					fclazz : ((p == 1) ? "hide" : ""),
					first : 1
				})));
	});
}

function checkText(type, id, count) {
	type = type.replace(new RegExp("'", 'g'), "");
	var v = $.trim($('#' + type + "_" + id).val());
	var left = calWbText(v, count);
	if (left >= 0) {
		$('#' + type + "_warn_" + id).html('还能输入<em>' + left + '</em>字');
	} else {
		$('#' + type + "_warn_" + id).html('已超出<em style="color:red;">' + Math.abs(left) + '</em>字');
	}
	return left >= 0 && v;
}
function calWbText(text, count) {
	var cLen = 0;
	var matcher = text.match(/[^\x00-\xff]/g),
	wlen = (matcher && matcher.length) || 0;
	return Math.floor((count * 2 - text.length - wlen) / 2);
}

/**
 *转发
 */
function send_zf(id, pl) {
	if (SENDING)
		return;
	var status = $.trim($("#zfTxt_" + id, $('div.tabpage:visible')).val());
	var color = "";
	if (!pl)
		color = $("#zfTxt_warn_" + id + " em", $('div.tabpage:visible')).prop("style").color;
	if (color != 'red') {
		if (pl)
			status = pl;

		SENDING = true;
		G.post(bg.APIV.statuses.repost, {
			id : id,
			is_comment : $("#zf_pl_" + id, $('div.tabpage:visible')).prop("checked") ? 3 : 0,
			status : status ? status : ""
		}, function (rsp) {
			if (!rsp.error) {
				G.showMsgNotification("操作成功!");
				if (!pl) {
					$("#home_zfWrap_" + id, $('div.tabpage:visible')).remove();
				} else {
					$("#home_plWrap_" + id, $('div.tabpage:visible')).remove();
				}

			}

			SENDING = false;
		});
	}
}

/**
 *评论微博
 */
function send_pl(id) {
	if (SENDING)
		return;
	var status = $.trim($("#plTxt_" + id, $('div.tabpage:visible')).val());
	var color = $("#plTxt_warn_" + id + " em", $('div.tabpage:visible')).prop("style").color;
	if (status && color != 'red') {
		SENDING = true;
		G.post(bg.APIV.comments.create, {
			id : id,
			comment : status ? status : ""
		}, function (rsp) {
			if (!rsp.error) {
				if ($("#pl_zf_" + id, $('div.tabpage:visible')).prop("checked")) {
					SENDING = false;
					send_zf(id, status);
				} else {
					G.showMsgNotification("操作成功!");
					$("#home_plWrap_" + id, $('div.tabpage:visible')).remove();
					SENDING = false;
				}
			} else {
				SENDING = false;
			}
		});
	}
}
/**
 *回复评论
 */
function send_pl_rp(id, mid, target) {
	if (SENDING)
		return;
	var status = $.trim($("#plTxt_" + (target ? mid : id), $('div.tabpage:visible')).val());
	var color = $("#plTxt_warn_" + (target ? mid : id) + " em", $('div.tabpage:visible')).prop("style").color;
	if (status && color != 'red') {
		SENDING = true;
		G.post(bg.APIV.comments.reply, {
			cid : id,
			id : mid,
			comment : status ? status : "",
			without_mention : 1
		}, function (rsp) {
			if (!rsp.error) {
				if ($("#pl_zf_" + (target ? mid : id), $('div.tabpage:visible')).prop("checked")) {
					SENDING = false;
					send_zf(mid, status);
				} else {
					G.showMsgNotification("操作成功!");
				}
				if (target) {
					$("#plTxt_warn_" + mid, $('div.tabpage:visible')).next("input").attr("onclick", "send_pl(" + mid + ")");
					$("#plTxt_" + mid, $('div.tabpage:visible')).val("");
				} else {
					$("#home_plWrap_" + id, $('div.tabpage:visible')).remove();
				}
			}
			SENDING = false;
		});
	}
}

function doDestroy(id) {
	G.post(bg.APIV.comments.destroy, {
		cid : id
	}, function (rsp) {
		if (!rsp.error) {
			G.showMsgNotification("操作成功!");
			$("#wb_" + id, $('div.tabpage:visible')).remove();
		}
	});
}

function doane(event) {
	e = event ? event : window.event;
	e.stopPropagation();
	e.preventDefault();
}

var imgTarget, infoTarget;
function showInfo(target) {
	if (target && target != imgTarget) {
		imgTarget = target;
		$(".user_info,.info_unset").hide();
		$(target).next().show();
		var info = $(target).parent().next();
		infoTarget = info[0];
		info.unbind().mouseout(function (event) {
			if (event.relatedTarget.nodeName != "P" && event.relatedTarget != imgTarget && event.relatedTarget != infoTarget) {
				hideInfo(this);
			}
		});
		info.fadeIn();
	}
}
function hideInfo(target) {
	$(target).prev().children("a").hide();
	$(target).fadeOut();
	imgTarget = null;
	infoTarget = null;
}

/****分页操作****/
function get_status(type, p) {
	p = parseInt(p);
	var request = {
		'count' : 50,
		'page' : p,
		'feature' : feature
	};
	$("#tabpage_status").html('<div style="text-align:center;"><img src="/waiting.gif"/></div>');
	G.gets(statuses_api_url, request, function (rsp) {
		var status_html = '';
		var _status = rsp.statuses;
		for (var idx in _status) {
			status_html += generateStatusDiv(_status[idx]);
		}
		$("#tabpage_status").html(ReplaceMethos(status_html));
		var next = p;
		var totalPage = Math.ceil(rsp.total_number / 50);
		if (p != totalPage) {
			next = p + 1;
		}
		if (rsp.total_number > 50) {
			$("#tabpage_status").append(ReplaceMethos(G.replaceAll(pageTpl, {
						id : "gsweibo",
						prev : p - 1,
						next : next,
						clasz : ((p == totalPage) ? "hide" : ""),
						clazz : ((p == 1) ? "hide" : ""),
						fclazz : ((p == 1) ? "hide" : ""),
						first : 1,
						method : "status"
					})));
		}
	});
}

function get_cmts(type, p) {
	p = parseInt(p);
	var request = {
		'page' : p
	};
	$("#tabpage_cmts").html('<div style="text-align:center;"><img src="/waiting.gif"/></div>');
	G.gets(comment_api_url, request, function (rsp) {
		var cmt_html = '';
		var _comments = rsp.comments;
		for (var idx in _comments) {
			cmt_html += generateCommentsDiv(_comments[idx]);
		}
		$("#tabpage_cmts").html(ReplaceMethos(cmt_html));
		var next = p;
		var totalPage = Math.ceil(rsp.total_number / 50);
		if (p != totalPage) {
			next = p + 1;
		}
		if (rsp.total_number > 50) {
			$("#tabpage_cmts").append(ReplaceMethos(G.replaceAll(pageTpl, {
						id : "gscmts",
						prev : p - 1,
						next : next,
						clasz : ((p == totalPage) ? "hide" : ""),
						clazz : ((p == 1) ? "hide" : ""),
						fclazz : ((p == 1) ? "hide" : ""),
						first : 1,
						method : "cmts"
					})));
		}
	});
}

function get_atme(type, p) {
	p = parseInt(p);
	var request = {
		'page' : p
	};
	$("#tabpage_atme").html('<div style="text-align:center;"><img src="/waiting.gif"/></div>');
	G.gets(comment_api_url, request, function (rsp) {
		var cmt_html = '';
		var _comments = rsp.comments;
		for (var idx in _comments) {
			cmt_html += generateArmeCommentsDiv(_comments[idx]);
		}
		$("#tabpage_atme").html(ReplaceMethos(cmt_html));
		var next = p;
		var totalPage = Math.ceil(rsp.total_number / 50);
		if (p != totalPage) {
			next = p + 1;
		}
		if (rsp.total_number > 50) {
			$("#tabpage_atme").append(ReplaceMethos(G.replaceAll(pageTpl, {
						id : "gsatme",
						prev : p - 1,
						next : next,
						clasz : ((p == totalPage) ? "hide" : ""),
						clazz : ((p == 1) ? "hide" : ""),
						fclazz : ((p == 1) ? "hide" : ""),
						first : 1,
						method : "atme"
					})));
		}
	});
}

function get_atmewb(type, p) {
	p = parseInt(p);
	var request = {
		'page' : p
	};
	$("#tabpage_atmewb").html('<div style="text-align:center;"><img src="/waiting.gif"/></div>');
	G.gets(at_mention_api_url, request, function (rsp) {
		var cmt_html = '';
		var _statuses = rsp.statuses;
		for (var idx in _statuses) {
			cmt_html += generateStatusDiv(_statuses[idx]);
		}
		$("#tabpage_atmewb").html(ReplaceMethos(cmt_html));
		var next = p;
		var totalPage = Math.ceil(rsp.total_number / 50);
		if (p != totalPage) {
			next = p + 1;
		}
		if (rsp.total_number > 50) {
			$("#tabpage_atmewb").append(ReplaceMethos(G.replaceAll(pageTpl, {
						id : "gsatmewb",
						prev : p - 1,
						next : next,
						clasz : ((p == totalPage) ? "hide" : ""),
						clazz : ((p == 1) ? "hide" : ""),
						fclazz : ((p == 1) ? "hide" : ""),
						first : 1,
						method : "atmewb"
					})));
		}
	});
}

function get_fans(type, p) {
	p = parseInt(p);
	var request = {
		'cursor' : (p - 1) * 50,
		'uid' : G.get('uid')
	};
	$("#tabpage_fans").html('<div style="text-align:center;"><img src="/waiting.gif"/></div>');
	G.gets(follower_api_url, request, function (rsp) {
		var follower_list = rsp['users'];
		var follower_html = '';
		for (var idx in follower_list) {
			follower_html += generateFollowerDiv(follower_list[idx]);
		}
		$("#tabpage_fans").html(ReplaceMethos(follower_html));
		var next = p;
		var totalPage = Math.ceil(rsp.total_number / 50);
		if (p != totalPage) {
			next = p + 1;
		}
		if (rsp.total_number > 50) {
			$("#tabpage_fans").append(ReplaceMethos(G.replaceAll(pageTpl, {
						id : "gsfans",
						prev : p - 1,
						next : next,
						clasz : ((p == totalPage) ? "hide" : ""),
						clazz : ((p == 1) ? "hide" : ""),
						fclazz : ((p == 1) ? "hide" : ""),
						first : 1,
						method : "fans"
					})));
		}
	});
}

function get_about(type, p) {
	p = parseInt(p);
	var request = {
		'count' : 10,
		'page' : p,
		'q' : type
	};
	$("#tabpage_about").html('<div style="text-align:center;"><img src="/waiting.gif"/></div>');
	G.gets(topics_api_url, request, function (rsp) {
		var status_html = '';
		var _status = rsp.statuses;
		for (var idx in _status) {
			status_html += generateStatusDiv(_status[idx]);
		}
		$("#tabpage_about").html(ReplaceMethos(status_html));
		var next = p;
		var totalPage = Math.ceil(rsp.total_number / 10);
		if (p != totalPage) {
			next = p + 1;
		}
		if (rsp.total_number > 10) {
			$("#tabpage_about").append(ReplaceMethos(G.replaceAll(pageTpl, {
						id : "gsabout",
						prev : p - 1,
						next : next,
						clasz : ((p == totalPage) ? "hide" : ""),
						clazz : ((p == 1) ? "hide" : ""),
						fclazz : ((p == 1) ? "hide" : ""),
						first : 1,
						method : "about",
						type:'GodSon分享'
					})));
		}
	});
}

function get_topic(type, p) {
	p = parseInt(p);
	var request = {
		'count' : 10,
		'page' : p,
		'q' : type
	};
	$("#tabpage_topic").html('<div style="text-align:center;"><img src="/waiting.gif"/></div>');
	G.gets(topics_api_url, request, function (rsp) {
		var status_html = '';
		var _status = rsp.statuses;
		for (var idx in _status) {
			status_html += generateStatusDiv(_status[idx]);
		}
		$("#tabpage_topic").html(ReplaceMethos(status_html));
		var next = p;
		var totalPage = Math.ceil(rsp.total_number / 10);
		if (p != totalPage) {
			next = p + 1;
		}
		if (rsp.total_number > 10) {
			$("#tabpage_topic").append(ReplaceMethos(G.replaceAll(pageTpl, {
						id : "gstopic",
						prev : p - 1,
						next : next,
						clasz : ((p == totalPage) ? "hide" : ""),
						clazz : ((p == 1) ? "hide" : ""),
						fclazz : ((p == 1) ? "hide" : ""),
						first : 1,
						method : "topic",
						type:type
					})));
		}
	});
}

function get_userStatus(type, p) {
	p = parseInt(p);
	var request = {
		'count' : 50,
		'page' : p,
		'screen_name' : type
	};
	$("#tabpage_info").html('<div style="text-align:center;"><img src="/waiting.gif"/></div>');
	G.gets(user_timeline, request, function (rsp) {
		var status_html = '';
		var _status = rsp.statuses;
		for (var idx in _status) {
			status_html += generateStatusDiv(_status[idx]);
		}
		$("#tabpage_info").html(ReplaceMethos(status_html));
		var next = p;
		var totalPage = Math.ceil(rsp.total_number / 50);
		if (p != totalPage) {
			next = p + 1;
		}
		if (rsp.total_number > 50) {
			$("#tabpage_info").append(ReplaceMethos(G.replaceAll(pageTpl, {
						id : "userweibo",
						type : type,
						prev : p - 1,
						next : next,
						clasz : ((p == totalPage) ? "hide" : ""),
						clazz : ((p == 1) ? "hide" : ""),
						fclazz : ((p == 1) ? "hide" : ""),
						first : 1,
						method : "userStatus"
					})));
		}
	});
}

function showFace(target) {
	console.log($(target).closest('div.btn').prev().children('textarea'));
	var showid = $(target).closest('div.btn').prev().children('textarea').attr('id');
	var wrap = $("#faceWraps");
	if (wrap.html() == "") {
		wrap.html(FACE_HTML);
	}
	wrap.children().unbind('click').click(function () {
		insertFace(showid, $(this).attr("title"));
	});

	var offset = $(target).offset();
	wrap.css({
		left : offset.left,
		top : offset.top
	});
	wrap.show();

	doane();
	$(document.body).unbind('click').click(function (e) {
		wrap.hide();
	});
	$(document).unbind('click').scroll(function (e) {
		wrap.hide();
	});
}

function insertFace(showid, text) {
	console.log(showid);
	var obj = document.getElementById(showid);
	selection = document.selection;
	checkFocus(showid);
	var opn = obj.selectionStart + 0;
	obj.value = obj.value.substr(0, obj.selectionStart) + text + obj.value.substr(obj.selectionEnd);
	var arra = showid.split("_");
	checkText(arra[0], arra[1], 140);
}

function isUndefined(variable) {
	return typeof variable == 'undefined' ? true : false;
}

function checkFocus(target) {
	var obj = document.getElementById(target);
	if (obj != null && !obj.hasfocus) {
		obj.focus();
	}
}

function imgEror(target) {
	target.src = '/maincss/404.png';
}

function showStatus(target, scname) {
	var scname = scname || $(target).text();
	if ($.trim(scname)) {
		$("#tabpage_info").html('<div style="text-align:center;"><img src="/waiting.gif"/></div>');
		$("#tabHeader_info").text(scname).show().click();
		G.gets(user_timeline, {
			screen_name : $.trim(scname)
		}, function (rsp) {
			var status_html = '';
			var _status = rsp.statuses;
			for (var idx in _status) {
				status_html += generateStatusDiv(_status[idx]);
			}
			var $status_html = ReplaceMethos(status_html);
			$("#tabpage_info").html($status_html);
			if (rsp.total_number > 50) {
				$("#tabpage_info").append(ReplaceMethos(G.replaceAll(pageTpl, {
							id : "userweibo",
							type : $.trim(scname),
							prev : 0,
							next : 2,
							clazz : "hide",
							fclazz : "hide",
							method : "userStatus"
						})));
			}
		});
	}
}

function showTopic(target) {
	var topic = $(target).text();
	topic = topic.replace(new RegExp("#", "gm"), '');
	$("#topicInput").val(topic);
	getTopic(topic);
}

function jumpUrl(target) {
	var url = $(target).text();
	G.gets(short_url_info, {
		url_short : encodeURI(url)
	}, function (rsp) {
		var info = rsp.urls[0];
		var url_long = info.url_long;
		var type = info.type;
		var annotations = info.annotations[0];
		if(annotations && (type ==1 || type == 2)){
			var url = '';
			if(type == 1){
				url = annotations.url;
			}else{
				if(annotations.player_url){
					url = annotations.player_url;
				}else{
					chrome.tabs.create({ url:annotations.url,selected:true });
					return;
				}
			}
			var left = (window.screen.width-700)/2;
			var top = (window.screen.height-500)/2;
			window.open(url,'','height=500,width=700,top='+top+',left='+left+',toolbar=no,menubar=no,scrollbars=no, resizable=no,location=no, status=no');
		}else{
			chrome.tabs.create({ url:url_long,selected:true });
		}
	});
}
var Methods = {
	doComment : doComment,
	doCommentZf : doCommentZf,
	doFavorited : doFavorited,
	doReposts : doReposts,
	doRepostsZf : doRepostsZf,
	follow_one : follow_one,
	hideLarge : hideLarge,
	showLarge : showLarge,
	showInfo : showInfo,
	get_user_info : get_user_info,
	imgEror : imgEror,
	doDestroy : doDestroy,
	doCommentCm : doCommentCm,
	checkText : checkText,
	send_zf : send_zf,
	send_pl : send_pl,
	send_pl_rp : send_pl_rp,
	doRePl : doRePl,
	get_reposts : get_reposts,
	get_comments : get_comments,
	get_about : get_about,
	get_topic : get_topic,
	get_atme : get_atme,
	get_cmts : get_cmts,
	get_atmewb : get_atmewb,
	get_fans : get_fans,
	get_status : get_status,
	get_userStatus : get_userStatus,
	showFace : showFace,
	showStatus : showStatus,
	showTopic : showTopic,
	jumpUrl : jumpUrl
};

function RefactorEvent(target, etype, mtName, params) {
	var mths = Methods[mtName];
	$(target).on(etype, function () {
		if (params) {
			if (params.length == 1) {
				if (params[0] == "this") {
					mths.call(this, this);
				} else {
					mths.call(this, params[0]);
				}
			}
			if (params.length == 2) {
				if (params[0] == "this") {
					mths.call(this, this, params[1]);
				} else {
					mths.call(this, params[0], params[1]);
				}
			}
			if (params.length == 3) {
				if (params[0] == "this") {
					mths.call(this, this, params[1], params[2]);
				} else {
					mths.call(this, params[0], params[1], params[2]);
				}
			}
		} else {
			mths.call(this);
		}
	});
}

function MethosR(evt, html) {
	var $html = $(html);
	$.each(evt, function (k, v) {
		$("[" + v + "]", $html).each(function () {
			var clk = $(this).attr(v);
			var mt = clk.substring(0, clk.indexOf("("));
			var params = clk.substring(clk.indexOf("(") + 1, clk.length - 1).split(',');
			RefactorEvent(this, v.substring(2, v.length), mt, params);
			$(this).removeAttr(v);
		});
	});
	return $html;
}

function ReplaceMethos(html) {
	return MethosR(["onclick", "onmouseover", "onerror", "onkeyup"], html);
}
var statusLoading = false;
var feature = 0;
function getStatuses(type) {
	feature = type;
	statusLoading = true;
	$("#tabpage_status").html('<div style="text-align:center;"><img src="/waiting.gif"/></div>');
	G.gets(statuses_api_url, {
		feature : type
	}, function (rsp) {
		var status_html = '';
		var _status = rsp.statuses;
		for (var idx in _status) {
			status_html += generateStatusDiv(_status[idx]);
		}
		var $status_html = ReplaceMethos(status_html);
		$("#tabpage_status").html($status_html);
		if (rsp.total_number > 50) {
			$("#tabpage_status").append(ReplaceMethos(G.replaceAll(pageTpl, {
						id : "gsweibo",
						prev : 0,
						next : 2,
						clazz : "hide",
						fclazz : "hide",
						method : "status"
					})));
		}
		statusLoading = false;
	});
}

$(function () {
	var status_num = cmt_num = fol_num = dm_num = men_num = atcmt_num = 0;

	//最新微博
	getStatuses(0);

	//评论
	G.gets(comment_api_url, {}, function (rsp) {
		var cmt_html = '';
		var _comments = rsp.comments;
		for (var idx in _comments) {
			cmt_html += generateCommentsDiv(_comments[idx]);
		}
		$("#tabpage_cmts").html(ReplaceMethos(cmt_html));
		if (rsp.total_number > 50) {
			$("#tabpage_cmts").append(ReplaceMethos(G.replaceAll(pageTpl, {
						id : "gscmts",
						prev : 0,
						next : 2,
						clazz : "hide",
						fclazz : "hide",
						method : "cmts"
					})));
		}
	});

	//@我的评论
	G.gets(mention_api_url, {}, function (rsp) {
		var cmt_html = '';
		var _comments = rsp.comments;
		for (var idx in _comments) {
			cmt_html += generateArmeCommentsDiv(_comments[idx]);
		}
		$("#tabpage_atme").html(ReplaceMethos(cmt_html));
		if (rsp.total_number > 50) {
			$("#tabpage_atme").append(ReplaceMethos(G.replaceAll(pageTpl, {
						id : "gsatme",
						prev : 0,
						next : 2,
						clazz : "hide",
						fclazz : "hide",
						method : "atme"
					})));
		}
	});

	//@我的微博
	G.gets(at_mention_api_url, {}, function (rsp) {
		var cmt_html = '';
		var _statuses = rsp.statuses;
		for (var idx in _statuses) {
			cmt_html += generateStatusDiv(_statuses[idx]);
		}
		$("#tabpage_atmewb").html(ReplaceMethos(cmt_html));
		if (rsp.total_number > 50) {
			$("#tabpage_atmewb").append(ReplaceMethos(G.replaceAll(pageTpl, {
						id : "gsatmewb",
						prev : 0,
						next : 2,
						clazz : "hide",
						fclazz : "hide",
						method : "atmewb"
					})));
		}
	});

	G.gets(follower_api_url, {
		'uid' : G.get('uid')
	}, function (rsp) {
		var follower_list = rsp['users'];
		var follower_html = '';
		for (var idx in follower_list) {
			follower_html += generateFollowerDiv(follower_list[idx]);
		}
		$("#tabpage_fans").html(ReplaceMethos(follower_html));
		if (rsp.total_number > 50) {
			$("#tabpage_fans").append(ReplaceMethos(G.replaceAll(pageTpl, {
						id : "gsfans",
						prev : 0,
						next : 2,
						clazz : "hide",
						fclazz : "hide",
						method : "fans"
					})));
		}
	});

	G.gets(topics_api_url, {
		'q' : 'GodSon分享'
	}, function (rsp) {
		var status_html = '';
		var _status = rsp.statuses;
		for (var idx in _status) {
			status_html += generateStatusDiv(_status[idx]);
		}
		$("#tabpage_about").html(ReplaceMethos(status_html));
		if (rsp.total_number > 10) {
			$("#tabpage_about").append(ReplaceMethos(G.replaceAll(pageTpl, {
						id : "gsabout",
						prev : 0,
						next : 2,
						clazz : "hide",
						fclazz : "hide",
						method : "about",
						type : 'GodSon分享'
					})));
		}
	});
});

function getTopic(topic) {
	$("#tabHeader_info").hide();
	$("#tabpage_info").empty();
	$("#tabHeader_topic").attr("title", "话题:" + topic).show().click();
	G.gets(topics_api_url, {
		'q' : topic
	}, function (rsp) {
		var status_html = '';
		var _status = rsp.statuses;
		for (var idx in _status) {
			status_html += generateStatusDiv(_status[idx]);
		}
		if (status_html) {
			$("#tabpage_topic").html(ReplaceMethos(status_html));
		} else {
			$("#tabpage_topic").html("没有找到相关微博！");
		}
		if (rsp.total_number > 10) {
			$("#tabpage_topic").append(ReplaceMethos(G.replaceAll(pageTpl, {
						id : "gstopic",
						prev : 0,
						next : 2,
						clazz : "hide",
						fclazz : "hide",
						method : "topic",
						type : topic
					})));
		}
	});
}
$(function () {
	$("#tabHeader_info").dblclick(function () {
		$("#tabHeader_status").click();
		$(this).hide();
		$("#tabpage_info").empty();
	});

	$("#tabHeader_topic").dblclick(function () {
		$("#tabHeader_status").click();
		$(this).hide();
		$("#tabpage_topic").empty();
		$("#topicInput").val("")
	});

	$("#topicButton").click(function () {
		var tp = $.trim($("#topicInput").val());
		if (tp) {
			getTopic(tp);
		}
	});

	$('#tab_nosep a').click(function () {
		if (statusLoading)
			return false;
		$('#tab_nosep a').removeClass("select");
		$(this).addClass('select');
		var type = $(this).attr("type");
		getStatuses(type);
	});
	
	setTimeout(function(){
		G.clearCounts();
	},1000);

	var isTop = false;
	$(document).scroll(function () {
		var top = $(this).scrollTop();
		if (top > 30) {
			if (!isTop) {
				$(".tabs").appendTo(".fixtop").addClass("headerTop");
			}
			isTop = true;
		} else {
			if (isTop) {
				$(".tabs").prependTo("#tabContainer").removeClass("headerTop");
			}
			isTop = false;
		}
	});
});
